
var Hex=require("./hex");
export function getBarcode(buffer) {
  var type = buffer[1];
  if (type == 0x61) {
    return getBarcode61(buffer);
  }
  if (type == 0x41) {
    if(buffer[2]==0x42){
      return getBarcode4142(buffer)
    }
    return getBarcode41(buffer);
  }
  if(type==0x21){
    return  getBarcode21(buffer);
  }
  if(type==0x11){
    return getBarcode11(buffer);
  }
  if(type==0xA1){
    return getBarcodeA1(buffer);
  }
  if(type==0xE1){
    return getBarcodeE1(buffer);
  }
}
export function getBlock(barcode){
  var info=wx.getStorageSync('info') ;
  var acsStr = "AB" + barcode + "|" + "AO" + info.libcode + "|AQ" + info.workLocationCode+"#";
  var buffer=[];
  for(var i=0;i<acsStr.length;i++){
    buffer.push(acsStr.charCodeAt(i));
  }
  return buffer;
}
function getBarcodeE1(buffer){
  var length=4+buffer[3];
  var acs="";
  for(var i=4;i<length;i++){
    acs+=String.fromCharCode(buffer[i]);
  }
  return acs
}
function getBarcodeA1(buffer){
  var length=buffer[3];
  var hexstr=Hex.bytesToHex(buffer.slice(4,4+length));
  return hexstr;
}
function getBarcode11(buffer){
  var length=buffer[2];
  var data=buffer.slice(3,7);
  return new DataView(data.buffer).getInt32();
}
function getBarcode21(buffer){
  var length=buffer[2];
  if(length>11){
    var acs="";
    for(var i=3;i<length+3;i++){
      acs+=String.fromCharCode(buffer[i]);
    }
    return acs;
  }

  var hexstr=Hex.bytesToHex(buffer.slice(3,3+length));
  return hexstr;
}

function getBarcode4142(buffer){
    var acs="";
    for(var i=1;i<buffer.length;i++){
      acs+=String.fromCharCode(buffer[i]);
    }
    var items=acs.split("|");
    for(var item of items){
      if(item.startsWith("AB")){
        return item.substring(2);
      }
    }
}
function getBarcode41(buffer) {
  var length = 3 + buffer[2];
  var list = [];
  for (var i = 3; i < length; i++) {
    list.push(buffer[i]);
  }
  var barCode = "";
  for (var i = 0; i < list.length / 3; i++) {
    var f = list[i * 3];
    var m = list[i * 3 + 1];
    var l = list[i * 3 + 2];
    if (f - 192 > 0) {
      barCode += parseInt((f - 192) / 4);
    } else {
      barCode += String.fromCharCode(f / 4 + 64);
    }
    if (f % 4 - 2 > 0) {
      barCode += parseInt(m / 16);
    } else {
      barCode += String.fromCharCode(f % 2 * 32 + m / 16 + 64);
    }
    if (m % 16 - 8 > 0) {
      barCode += parseInt(m % 4 * 4 + l / 64);
    } else {
      barCode += String.fromCharCode(m % 8 * 4 + l / 64 + 64);
    }
    if (l % 64 - 32 > 0) {
      barCode += parseInt(l % 16);
    } else {
      barCode += String.fromCharCode(l % 32 + 64);
    }
  }
  return barCode;
}

function getBarcode61(buffer) {
  var length = 3 + buffer[2];
  var chars = [];
  for (var i = 3; i < length; i++) {
    chars.push(String.fromCharCode(buffer[i]));
  }
  return chars.join("");
}